import { Component, OnInit } from "@angular/core";
import { NzMessageService, NzModalService, UploadFile } from "ng-zorro-antd";
import { FileImportHttpService } from "../services/file-import.service";

@Component({
  selector: "app-base-upload",
  templateUrl: "./base-upload.component.html",
  styleUrls: ["./base-upload.component.less"],
})
export class BaseUploadComponent implements OnInit {
  uploading = false;
  fileList: UploadFile[] = [];

  constructor(
    private msg: NzMessageService,
    private http: FileImportHttpService,
    private modalService: NzModalService
  ) {}

  ngOnInit() {}

  beforeUpload = (file: UploadFile): boolean => {
    // 检查是否已经有文件在列表中，以下注释代码将禁止上传，目前是上传替换（后面上传会替换前面）
    // if (this.fileList.length > 0) {
    //   this.msg.error("每次只能上传一个文件！");
    //   return false;
    // }

    // 检查文件类型是否为.csv
    const isCSV =
        file.type === 'text/csv' ||
        file.name.slice(-4).toLowerCase() === '.csv';
    if (!isCSV) {
        this.msg.error('只能上传CSV文件！');
        return false;
    }

    // 检查文件大小是否超过30MB
    const isLt30M = file.size / 1024 / 1024 < 30;
    if (!isLt30M) {
      this.msg.error("文件必须小于30MB！");
      return false;
    }

    // this.fileList = this.fileList.concat(file);
    this.fileList = [file];
    return false;
  };

  handleUpload(): void {
    const formData = new FormData();
    this.fileList.forEach((file: any) => {
      formData.append("file", file);
    });
    this.uploading = true;
    this.http.uploadBase(formData).subscribe(
      (res) => {
        if (res.status === 200) {
          this.msg.success(res.msg);
          // this.getImportResult({key:res.data});
        } else {
          this.msg.error(res.msg);
        }
        this.uploading = false;
      },
      (error) => {
        this.uploading = false;
        this.msg.error("上传失败");
      }
    );
  }

  getImportResult(data: any): void {
    this.http.getImportResult(data).subscribe((res) => {
      console.log(92, res);
      if (res.status === 200) {
        this.msg.success(res.msg.message);
        this.uploading = false;
      } else {
        this.uploading = false;
        this.msg.error(res.msg.message);
        this.modalService.confirm({
          nzTitle: "是否下载错误详情文件?",
          // nzContent: '<b style="color: red;">Some descriptions</b>',
          nzOkText: "下载错误文件",
          // nzOkType: 'danger',
          nzOnOk: () => this.downloadErrorFile(res.msg.error_file),
          nzCancelText: "取消",
          nzOnCancel: () => console.log("Cancel"),
        });
        // this.downloadErrorFile(res.msg.error_file);
      }
    });
  }

  private downloadErrorFile(filePath: string): void {
    const url = `/logcollect/api/v1/analysis_result_view/result_download_txt?file_path=${filePath}`;
    fetch(url)
      .then((response) => response.blob())
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = filePath || "错误结果.txt";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url); // 清理URL对象
      })
      .catch((error) => {
        this.msg.error("下载文件失败");
        console.error("下载文件失败:", error);
      });
  }
}
